---
name: usePrevious
route: /usePrevious
menu: 'State'
edit: false
sidebar: true
---

import JackBox from 'jackbox';

import Demo1 from './demo/demo1';
import Demo1CodeTsx from '!raw-loader!./demo/demo1.tsx';
import Demo1CodeJsx from '!raw-loader!./demo/demo1.jsx';

import Demo2 from './demo/demo2';
import Demo2CodeJsx from '!raw-loader!./demo/demo2.jsx';
import Demo2CodeTsx from '!raw-loader!./demo/demo2.tsx';


# usePrevious

A Hook to store the previous value


## Examples

### Default usage

<JackBox jsCode={Demo1CodeJsx} tsCode={Demo1CodeTsx} demoName='Default usage' description='Store the previous value'>
  <Demo1 />
</JackBox>

### Using compare function

<JackBox jsCode={Demo2CodeJsx} tsCode={Demo2CodeTsx} demoName=' Using compare function' description='The stored previous value update only when the compare function returns true'>
  <Demo2 />
</JackBox>

## API
```
const previousState: T = usePrevious<T>(
  state: T,
  compareFunction: (prev: T | undefined, next: T) => boolean
);
```

### Result

| Property | Description                                                       | Type                 |
|------|----------|------|
| previousState | the previous value | T  |

### Params

| Property | Description                                                       | Type                 | Default |
|---------|----------|------------------------|--------|
| state | the state need to be tracked | T | -      |
| compareFunction | optional, customize when the previous value need to be stored | (prev: T \| undefined, next: T) => boolean | -      |
